
'use strict';

const BaseService = require("./base");


class SubscribeService extends BaseService{

   // 获取列表 1-关注 2-粉丝
   async subscribeByUser(body){
        const obj = {
            guanzhu: ['subscribe_id','be_subscribe_id'],
            fensi: ['be_subscribe_id','subscribe_id'],
        } 
        const { AdminUser, AdminRoleUser } = this.app.model;
        const  params = this.app._.cloneDeep(body)
        const roleType = params.type === 1 ?obj.guanzhu:obj.fensi
        const {user_id} = params
        const where = {}
        where[roleType[0]] = user_id
        where.status = 1
        const beSubscribes = await this.app.model.Subscribe.findAll({
            attributes:{exclude:['delete_time',]},
            where:where
        })
        const userIds = beSubscribes.map(item=>Number(item[roleType[1]]))
        if(params.all){
            const beSubscribeUsers = await AdminUser.findAndCountAll({
                attributes:  [ 'id', 'username','avatar' ] ,
                where:{
                    id:userIds,
                    status:1
                }
            })
            return beSubscribeUsers.rows
        }else{
            const { count, rows } = await AdminUser.findAndCountAll({
              distinct: true,
              where: this.queryWhere(params,userIds),
              attributes:  [ 'id', 'username' ] ,
              include: [
                {
                  model: AdminRoleUser,
                  as: 'roles',
                  attributes: [ 'user_id', 'role_id' ],
                },
              ],
              ...this.pageParam(params),
            });
            return this.paginate(count, rows,params);
        }
   }

   queryWhere (params,userIds) {
    const { Op } = this.app.Sequelize;
    const where = {}; 
    where.id = userIds
    where.status = 1
    const gender = parseInt(params.gender)
    const searchWord =params.searchWord
    if(searchWord!==''){
      where[Op.and] = { username: { [Op.like]: `%${searchWord}%` } }
    }
    if (!isNaN(gender) && [ 0 ,1, 2 ].includes(gender)) {
      where.gender = gender;
    }
    return where;
  }


   //  关注 1，取关 0
   async changeSubscribeStatus(body){
    const  params = this.app._.cloneDeep(body)
    const {be_subscribe_id, subscribe_id,status} = params
    const curSub = await this.app.model.Subscribe.findOne({
        where:{
            be_subscribe_id,subscribe_id
        }
    })
    if(curSub){
        const {id} = curSub
        await this.app.model.Subscribe.update({status},{
            where:{
                id
            }
        })
    }else{
        params.create_time = new Date()
        params.status = 1
        await this.app.model.Subscribe.create(params)
    }
   }
}


module.exports = SubscribeService;